package com.losdun.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.losdun.product.controller.req.AttrRelatedReq;
import com.losdun.product.domain.AttributeRelated;
import com.losdun.product.mapper.AttributeRelatedMapper;
import com.losdun.product.service.IAttributeRelatedservice;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author sword.ye
 * @date 2025/3/4
 **/
@Service
public class AttributeRelatedserviceImpl extends ServiceImpl<AttributeRelatedMapper, AttributeRelated> implements IAttributeRelatedservice {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertAttrRelated(AttrRelatedReq req) throws Exception{
        if(req==null || req.getAttrId()==null){
            throw new RuntimeException("参数错误！");
        }
        //先删除再保存
        this.removeRelatedList(req.getAttrId(),req.getType());
        List<AttributeRelated> insertList=new ArrayList<>();
        if(req.getRequiredIds()!=null){
            List<AttributeRelated> requiredList= req.getRequiredIds().stream().map(rId->{
                AttributeRelated attrRelated=new AttributeRelated();
                attrRelated.setAttributeId(req.getAttrId());
                attrRelated.setRelatedId(rId);
                attrRelated.setType(req.getType());
                attrRelated.setIsRequired(1);
                return attrRelated;
            }).collect(Collectors.toList());
            insertList.addAll(requiredList);
        }
        if(req.getOptionIds()!=null){
            List<AttributeRelated> requiredList= req.getOptionIds().stream().map(rId->{
                AttributeRelated attrRelated=new AttributeRelated();
                attrRelated.setAttributeId(req.getAttrId());
                attrRelated.setRelatedId(rId);
                attrRelated.setType(req.getType());
                attrRelated.setIsRequired(0);
                return attrRelated;
            }).collect(Collectors.toList());
            insertList.addAll(requiredList);
        }
        this.saveBatch(insertList);
    }

    @Override
    public List<AttributeRelated> queryRelatedList(Long attrId, String type) {
        LambdaQueryWrapper<AttributeRelated> qw=new LambdaQueryWrapper<>();
        qw.eq(AttributeRelated::getAttributeId,attrId)
                .eq(AttributeRelated::getType,type);
        return this.list(qw);
    }

    private void removeRelatedList(Long attrId,String type){
        LambdaQueryWrapper<AttributeRelated> qw=new LambdaQueryWrapper<>();
        qw.eq(AttributeRelated::getAttributeId,attrId)
                .eq(AttributeRelated::getType,type);
        this.remove(qw);
    }
}
